# coding:utf-8

from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.contrib.auth.models import AbstractUser
from PIL import Image
import os


class ArticleManage(models.Manager):
    def get_recommend_article(self):
        query = self.get_queryset().order_by('-hot')[4:14]
        return query

    def get_hot_article(self):
        query = self.get_queryset().order_by('-hot')[:5]
        return query


@python_2_unicode_compatible
class User(AbstractUser):
    # cls.REQUIRED_FIELDS,
    # username = models.CharField(max_length=256)
    # password = models.CharField(max_length=256)
    name = models.CharField(max_length=256)
    icon = models.ImageField(upload_to='picture/%Y/%m/%d')
    text = models.CharField(default=" ", max_length=256)
    register_date = models.DateTimeField(auto_now_add=True, editable=True)
    near_login_date = models.DateTimeField(auto_now_add=True, editable=True)

    def __str__(self):
        return self.username

    def is_follow(self, request):
        if request.user.is_authenticated():
            follow = Follow.objects.filter(from_user=request.user, to_user=self).first()
            if follow:
                return 1
            else:
                return 0
        else:
            return 0

    def get_following(self, request):
        if request.user.is_authenticated():
            follow = Follow.objects.filter(from_user=request.user, to_user=self).first()
            if follow:
                self.following = 1
            else:
                self.following = 0
        else:
            self.following = 0

    def get_posts_count(self):
        count = Article.objects.filter(auther=self).count()
        return count
    def get_fans_count(self):
        count = Follow.objects.filter(to_user=self).count()
        return count
    def get_follows_count(self):
        count = Follow.objects.filter(from_user=self).count()
        return  count
    def get_likes_count(self):
        count = Like.objects.filter(user=self).count()
        return count

    def get_collects_count(self):
        count = Collect.objects.filter(user=self).count()
        return count

    def get_post_images(self):
        posts = Article.objects.filter(auther=self).order_by('-create_date')[:3]
        return posts

@python_2_unicode_compatible
class Comment(models.Model):
    user = models.ForeignKey(User,null=True)
    article_id = models.CharField(max_length=256)
    text = models.CharField(max_length=256)
    pub_date = models.DateTimeField()

    def __str__(self):
        return self.text

@python_2_unicode_compatible
class Leave(models.Model):
    user = models.ForeignKey(User,null=True)
    text = models.CharField(max_length=256)
    pub_date = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.text


@python_2_unicode_compatible
class Article(models.Model):
    title = models.CharField(max_length=256)
    images = models.TextField()
    thumb_images = models.TextField(default='')
    content = models.TextField()
    hot = models.IntegerField(default=0)
    auther = models.ForeignKey(User)
    create_date = models.DateTimeField()
    tag_text = models.CharField(max_length=256,default=' ')

    objects = ArticleManage()

    def __str__(self):
        return self.title

    def get_comments(self):
        return Comment.objects.filter(article_id=self.id)

    def get_like(self,request):
        if request.user.is_authenticated():
            like = Like.objects.filter(user=request.user,article=self).first()
            if like:
                self.like = 1
            else:
                self.like = 0
        else:
            self.like = 0

    def get_like_count(self):
        count = Like.objects.filter(article=self).count()
        return count
    def get_collect_count(self):
        count = Collect.objects.filter(article=self).count()
        return count

    def get_collect(self,request):
        if request.user.is_authenticated():
            collect = Collect.objects.filter(user=request.user,article=self).first()
            if collect:
                self.collect = 1
            else:
                self.collect = 0
        else:
            self.collect = 0

    def get_image_list(self):
        image_list = self.images.split(';')[0:3]
        return image_list

    def get_image_list(self):
        if self.thumb_images:
            image_list = self.thumb_images.split(';')
        else:
            image_list = self.images.split(';')
        return image_list


    def get_first_image(self):
        first_image = ''
        if self.thumb_images:
            first_image = self.thumb_images.split(';')[0]
        else:
            first_image = self.images.split(';')[0]
        return first_image


class Follow(models.Model):
    from_user = models.ForeignKey(User, related_name='from_user')
    to_user = models.ForeignKey(User, related_name='to_user')
    relation = models.BooleanField(default=False)


class Like(models.Model):
    user = models.ForeignKey(User, null=True)
    article = models.ForeignKey(Article, null=True)


class Collect(models.Model):
    user = models.ForeignKey(User, null=True)
    article = models.ForeignKey(Article, null=True)


class HotArticle(models.Model):
    article = models.ForeignKey(Article)
    sign_date = models.DateTimeField(auto_now_add=True, editable=True)


@python_2_unicode_compatible
class Recommend(models.Model):
    article = models.ForeignKey(Article)
    sign_date = models.DateTimeField()

    def __str__(self):
        return self.article.title


class UserImage(models.Model):
    user = models.ForeignKey(User)
    image = models.ImageField(upload_to='picture/%Y/%m/%d')
    thumb_image = models.CharField(max_length=256, default='')

    def get_thumb_path(self, path):
        thumb_all_name = path.split('/')
        ext = thumb_all_name[-1].split('.')[-1]
        name = thumb_all_name[-1].split('.')[0] + '_thumb'
        del thumb_all_name[-1]
        thumb_path = '/'.join(thumb_all_name) + '/' + name + '.' + ext
        return thumb_path

    def make_thumb(self):
        path = self.image.path.replace('\\', '/')
        pixbuf = Image.open(path)
        width, height = pixbuf.size
        bl = 345.0 / 270.0
        if height * bl > width:
            img = pixbuf.crop((0, int((height - (width / bl)) / 2), width, int(height - ((height - (width / bl)) / 2))))
        else:
            img = pixbuf.crop((int((width - (height * bl)) / 2), 0, int(width - ((width - (height * bl)) / 2)), height))
        img.thumbnail((345, 270), Image.ANTIALIAS)
        thumb_path = self.get_thumb_path(path)
        thumb_url = self.get_thumb_path(self.image.url)
        img.save(thumb_path)
        return thumb_url


class Type(models.Model):
    name = models.CharField(max_length=256)
    hot = models.IntegerField(default=0)  # 人气
    image = models.ImageField(upload_to='picture/type')

    def get_article_count(self):
        return Article_to_type.objects.filter(type_id=self).count()


class Article_to_type(models.Model):
    article_id = models.ForeignKey(Article)
    type_id = models.ForeignKey(Type)
